package cn.wk.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import cn.wk.services.ClassesServices;
import cn.wk.services.impl.Classesserviceslmpl;
import cn.wk.util.*;
@MultipartConfig
@WebServlet("/importclasses")
public class Servletimportclasses extends HttpServlet {
    private ClassesServices cs=new Classesserviceslmpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //需要上传，必须加入@MultipartConfig  注解
        //获取参数
        Part part=request.getPart("file");
        //获取文件名
        String filename=getFileName(part);
        //获取数据的流
        InputStream inputStream=part.getInputStream();
        ParseExcel pexcel=new ParseExcel();
        String[]suffx=filename.split("\\.");
        int startRow=1;
        String s=suffx[1];
        List<String[]>result= pexcel.parseExcel(inputStream,s,startRow);
        StringBuilder sb=new StringBuilder();
        sb.append("insert classes(cname)value");
        for(String[]ss:result){
            if(ss[0].equals("cname")) continue;
            sb.append("('");
            sb.append(ss[0]);
            sb.append("')");
            sb.append(",");
        }
        //找到最后一个，号，并删除
        int index=sb.toString().lastIndexOf(',');
        sb.deleteCharAt(index);
        sb.append(";");
        String sql=sb.toString();
        int b=cs.AddAllClasses(sql);
        s="";
        if(b>0){
            s="成功！";
            request.setAttribute("s",s);
            request.getRequestDispatcher("/class-addall.jsp").forward(request,response);
//            response.getWriter().println(JsonRes.res());
        }

        else{
            s="失败！";
            request.setAttribute("s",s);
            request.getRequestDispatcher("/class-addall.jsp").forward(request,response);
        }
//            response.getWriter().println("失败！");
//            response.getWriter().println(JsonRes.error());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);

    }
   private String getFileName(Part part){
        String head=part.getHeader("Content-Disposition");
        String fileName=head.substring(head.indexOf("filename=\"")+10,
                head.lastIndexOf("\""));
        return fileName;
   }
}
